<template>
	<view class="recording-row text-in theme-shadow mb-3">
		<view class="voice-box" @touchstart="recordStart" @touchend="recordStop" @click="record">
			<view class="play-title">录音</view>
			<view class="play-voice" v-if="voiceData.mediaId">
				<image src="../static/images/voice.png" mode="" />{{ voiceData.duration }}"
			</view>
			<view v-else class="none-voice"></view>
			<view class="action" v-if="!recordingFinished">
				按住 说话
			</view>
		</view>
	</view>
	<view class="modal" v-show="recording">
		<image src="../static/images/ic_voice.png" mode="aspectFill"></image>
	</view>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, Ref } from 'vue';
// #ifdef H5
import dd from "gdt-jsapi"
// #endif

const emit = defineEmits(['updateRecord'])

const voiceData:any = reactive({
	mediaId: "",
	duration: null,
	localAudioId: null
})
const recording:Ref<boolean> = ref(false)
const recordingFinished:Ref<boolean> = ref(false)
// const recordingLoading:Ref<boolean> = ref(false)

let recordingDownloadFinished = false
let playingLoading = false
let playing = false
let autoStopTimeout = null
	
const record = () => {
	if (voiceData.mediaId) {
		playVoice()
	}
}

const recordStart = ():void => {
	// console.log("点下")
	if (voiceData.mediaId) {
		// 如果已有录音文件 那么不录音
		return
	}
	
	dd.startRecordAudio({}).then((res) => {
		console.log(res)
		recording.value = true	
	}).catch(err => {
		console.log(err)
	})
}

const recordStop = ():void => {
	// uni.showToast({
	// 	icon: "none",
	// 	title: "弹起"
	// })
	dd.stopRecordAudio({}).then((res:any) => {
		recording.value = false
		recordingFinished.value = true
		// uni.showToast({
		// 	icon: "none",
		// 	title: "录音结束 mediaId:" + res.mediaId + " duration:" + res.duration
		// })
		voiceData.mediaId = res.mediaId
		voiceData.duration = Math.ceil(res.duration)
		emit("updateRecord", voiceData)
		voiceData.localAudioId = null
		recordingDownloadFinished = false
	}).catch(err => {
		recording.value = false
		// uni.showToast({
		// 	icon: "none",
		// 	title: "录音时长果断"
		// })
	})
}
const downloadVoice = ():Promise<void> => {
	return new Promise((resolve, reject):void => {
		dd.downloadAudio({
		  mediaId: voiceData.mediaId
		}).then((res:any) => {
			voiceData.localAudioId = res.localAudioId
			recordingFinished.value = true
			recordingDownloadFinished = true
			resolve()
		}).catch((err:any) => {
			uni.showToast({
				icon: "none",
				title: "录音下载失败" + JSON.stringify(err)
			})
			reject()
		})
	})
}
const playVoice = async () => {
	if (!recordingDownloadFinished) {
		await downloadVoice()
	}
	if (playingLoading) return
	if (playing) {
		playingLoading = true
		dd.stopAudio({
			localAudioId : voiceData.localAudioId,
		}).then((res) => {
			playingLoading = false
			playing = false
			clearTimeout(autoStopTimeout)
		}).catch((err) => {
			playingLoading = false
			uni.showToast({
				icon: "none",
				title: "录音停止失败" + JSON.stringify(err)
			})
		})
	} else {
		playingLoading = true
		dd.playAudio({
			localAudioId : voiceData.localAudioId,
		}).then((res) => {
			playing = true
			playingLoading = false
			
			autoStopTimeout = setTimeout(() => {
				playing = false
			}, voiceData.duration * 1000)
			
		}).catch(err => {
			playingLoading = false
			uni.showToast({
				icon: "none",
				title: "录音播放失败" + JSON.stringify(err)
			})
		})
	}
}

onMounted(() => {
	dd.onRecordAudioEnd({}).then((res) => {
		console.log("超时自动结束")
		voiceData.mediaId = res.mediaId
		voiceData.duration = Math.ceil(res.duration)
		emit("updateRecord", voiceData)
	}).catch((err) => {
		console.log(err)
	})
})

defineExpose({
	voiceData
})
</script>

<style lang="stylus" scoped>
.recording-row:active
	background: #eee
.recording-row
	padding 10rpx 40rpx
	background: #fff
	border-radius: 12rpx
.voice-box
	display: flex
	align-items: center
	height: 86rpx
	.play-title
		width: 80rpx
	.play-voice
		margin: 0 auto
		height: 66rpx
		width: 430rpx
		border-radius: 12rpx
		display: flex
		align-items: center
		font-weight: bold
		color #515151
		image
			width: 44rpx
			height: 44rpx
			padding: 11rpx
	.action
		width: 160rpx
		text-align: right
		color #999
	.none-voice
		width: 430rpx
		
.modal
	width: 200rpx
	height: 200rpx
	padding: 25rpx
	position: fixed
	background-color: rgb(0, 0, 0)
	top: calc(50vh - 100rpx)
	left: calc(50vw - 100rpx)
	opacity: 0.3
	border-radius: 12rpx
	image
		width: 100%
		height: 100%
</style>